#include "CSpeedometer.h"


CSpeedometer::CSpeedometer(IrrlichtDevice *device, vector2di position)
{
	driver = device->getVideoDriver();
	smgr = device->getSceneManager();

	this->position = position;

	// Load speedometer textures
	scaleTexture = driver->getTexture(L"data/textures/speedometer/scale.png");
	arrowTexture = driver->getTexture(L"data/textures/speedometer/arrow.png");

	// Set number of mesh buffers vertices and indeces
	planeMesh.Vertices.set_used(4); 
	planeMesh.Indices.set_used(6);

	SColor white(255, 255, 255, 255);

	// Set mesh buffers vertices
	planeMesh.Vertices[0] = S3DVertex(-1.f, -1.f, 0.f, 0.f, 0.f, 1.f, white, 0.f, 1.f); 
	planeMesh.Vertices[1] = S3DVertex(-1.f,  1.f, 0.f, 0.f, 0.f, 1.f, white, 0.f, 0.f); 
	planeMesh.Vertices[2] = S3DVertex( 1.f,  1.f, 0.f, 0.f, 0.f, 1.f, white, 1.f, 0.f); 
	planeMesh.Vertices[3] = S3DVertex( 1.f, -1.f, 0.f, 0.f, 0.f, 1.f, white, 1.f, 1.f);

	// Initialize the mesh buffer indices
	planeMesh.Indices[0] = 0; 
	planeMesh.Indices[1] = 1; 
	planeMesh.Indices[2] = 2; 
	planeMesh.Indices[3] = 2; 
	planeMesh.Indices[4] = 3; 
	planeMesh.Indices[5] = 0;

	// Set plane material and texture
	planeMesh.getMaterial().Lighting = false; 
	planeMesh.getMaterial().MaterialType = EMT_TRANSPARENT_ALPHA_CHANNEL;
	planeMesh.getMaterial().setTexture(0, arrowTexture);
}


CSpeedometer::~CSpeedometer(void)
{
}


// Rotates spedometer arrow on angle
void CSpeedometer::rotateArrow(f32 degrees) 
{ 
	matrix.makeIdentity(); 
	matrix.setRotationDegrees(vector3df(0, 0, degrees)); 
}


// Redraws speedometer
void CSpeedometer::update()
{
	// Draw speedometer texture
	driver->draw2DImage(scaleTexture, position, recti(0, 0, 
		scaleTexture->getOriginalSize().Width, scaleTexture->getOriginalSize().Height), 0, SColor(255,255,255,255), true);	
	
	// Store the old viewport
	recti oldViewPort = driver->getViewPort();
	
	// Create the new viewport
	recti newViewPort = recti(position, scaleTexture->getOriginalSize());
	driver->setViewPort(newViewPort); 

	// Store and clear the projection matrix
	matrix4 oldProjMat = driver->getTransform(ETS_PROJECTION); 
	driver->setTransform(ETS_PROJECTION, matrix4());

	// Store and clear the view matrix
	matrix4 oldViewMat = driver->getTransform(ETS_VIEW); 
	driver->setTransform(ETS_VIEW, matrix4()); 

	// Apply transformation matrix to the viewport
	driver->setTransform(ETS_WORLD, matrix); 
	driver->setMaterial(planeMesh.Material); 
	driver->drawMeshBuffer(&planeMesh); 

	// Restore viewport
	driver->setViewPort(oldViewPort);

	// Restore projection and view matrices
	driver->setTransform(ETS_PROJECTION, oldProjMat);
	driver->setTransform(ETS_VIEW, oldViewMat); 
}
